﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.DatabaseHelpers;
using Core.Interfaces;
using Core.Unity;
using Microsoft.Practices.Unity;

namespace Core.Domains
{
    
    public class Building:IBuilding
    {
        private int _flourNumber;
        private string _address = "";
        private DateTime _buildingDate;
        private string _regId;
        private List<IAction> _actions;
        private IDistrict _district;
        private bool _fromDB = false;
        private int _squere;
        private int _startprice = 0;
        public int FlourNumber
        {
            get { return _flourNumber; }
            set { _flourNumber = value; }
        }

        public string Address
        {
            get { return _address; }
            set { _address = value;}
        }

        public string RegisterID
        {
            get { return _regId; }
            set { _regId = value; }
        }

        public DateTime BuildingDate
        {
            get { return _buildingDate; }
            set { _buildingDate = value; }
        }

        public IDistrict District
        {
            get { return _district; }
            set { _district = value; }
        }

        public int Squere
        {
            get { return _squere; }
            set { _squere = value; }
        }

        public int StartPrice
        {
            get
            {
                if (_fromDB)
                {
                    var con = ResolverContainer.Resolver.Resolve<IConnection>();
                    var result = con.ExecuteSelectQuery(string.Format("select startprice from building_action where register_id='{0}'",_regId),1);
                    return result.Count() > 0 ? int.Parse( result.First()[0].ToString()) : 0;
                }
                return 0;

            }
            set { _startprice = value; }
        }

        public string DistrictName
        {
            get { return _district == null ? "Нет" : _district.Name; }
        }


        public Building()
        {}

        public void ConstructIt(object[] record)
        {
            _regId = record[0].ToString();
            _flourNumber = int.Parse(record[1].ToString());
            _buildingDate = DateTime.Parse(record[3].ToString());
            _address = record[2].ToString();
            _squere = int.Parse(record[4].ToString());
            _fromDB = true;
        }

        public bool FromDatabase()
        {
            return _fromDB; 
        }

        public string GetErrorByCode(int code)
        {
            if (code == 1451 || code == 547)
            {
                return "Здание было выставленно на аукцион";
            }
            return "";
        }

        public override string ToString()
        {
            return _regId + "/" + _address;
        }
    }
}
